package http;

import handle.MyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

import java.net.URI;

public class MyHttpClient1 {
    public static void main(String[] args) throws Exception
    {
        //只要一个线程组
        EventLoopGroup group=new NioEventLoopGroup();
        try{
            //启动实例是bootstrap
            Bootstrap b=new Bootstrap();
            b.group(group)
                    //连接类型是NioSocketChannel.class
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel sc) throws Exception {
                            //http编解码，和服务器不同
                            sc.pipeline().addLast(new HttpClientCodec());
                            sc.pipeline().addLast(new HttpObjectAggregator(65536));
                            sc.pipeline().addLast(new MyClientHandler());
                        }
                    });
            URI uri = new URI("http://127.0.0.1:8080");
            String msg = "hello";
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                    uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));
            request.headers().set("Content-Length", request.content().readableBytes());
            System.out.println("------客户端启动-------");
            Channel ch=b.connect("127.0.0.1",8080).sync().channel();
            ch.writeAndFlush(request).sync();
            ch.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

}
